<template>
  <div>
    <!-- 选择 -->
    <el-select
      v-model="selected"
      remote
      filterable
      clearable
      placeholder="请选择"
      :remote-method="remoteMethod"
      :readonly="readonly"
      @clear="clearMethod"
      @change="onSelectChanged"
    >
      <el-option
        v-for="opt in options"
        :key="opt.value"
        :label="opt.name"
        :value="opt.value"
      />
      <el-button
        v-if="hasNext"
        :loading="loading"
        type="primary"
        style="width:100%;"
        @click="nextPage"
      >加载更多</el-button>
    </el-select>
    <slot />
  </div>
</template>

<script>
import { getList, getMainName, getMainColName } from './apidefines'
import { concatUniq } from '@/utils'
export default {
  name: 'FromApiPage',
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    readonly: {
      type: Boolean,
      default: false
    },
    apiname: {
      type: String,
      default: function() {
        return ''
      }
    },
    value: {
      type: [Number, Object, String],
      default: function() {
        return {}
      }
    },
    query: {
      type: Object,
      default: function() {
        return {
          query: '',
          queryColumn: '',
          order: '',
          column: '',
          curPage: 1,
          pageSize: 20,
          queryList: {
            columns: []
          }
        }
      }
    },
    queryWith: {
      type: Array,
      default: function() {
        // return [{ name: '', value: '' }]
        return []
      }
    }
  },
  data() {
    return {
      loading: false,
      selected: '',
      form: {},
      options: [],
      listQuery: {
        query: '',
        queryColumn: '',
        order: '',
        column: '',
        curPage: 1,
        pageSize: 20,
        queryList: {
          columns: []
        }
      },
      listData: {
        current: 0,
        pages: 0,
        searchCount: true,
        size: 20,
        total: 0,
        records: []
      },
      lastQueryWith: []
    }
  },
  computed: {
    itemid() {
      return this.$route.params.id
    },
    cname() {
      return this.$route.params.cname
    },
    hasNext() {
      return this.listData.current < this.listData.pages
    }
  },
  watch: {
    apiname(newValues) {
      // this.fetchData()
    },
    value(newValues) {
      console.log('newValues', newValues)
      this.selected = newValues
      this.fetchValueData()
    },
    query(newValues) {
      // this.options = this.options.filter(v => v.value === this.selected)
      this.listQuery = newValues
    },
    queryWith(newValues) {
      console.log('queryWith', newValues)
      let same = true
      for (let i = 0; i < this.lastQueryWith.length && i < newValues.length; i++) {
        if (this.lastQueryWith[i].name !== newValues[i].name || this.lastQueryWith[i].value !== newValues[i].value) {
          same = false
          break
        }
      }
      if (!same) this.selected = ''
      this.lastQueryWith = newValues
      this.listQuery.curPage = 1
      this.options = []
      this.fetchData()
    }
  },
  mounted() {
    this.listQuery = this.query
    this.fetchValueData()
    this.fetchData()
  },
  methods: {
    // 获取当前条目信息
    fetchValueData() {
      const questArgs = {
        query: `${this.selected}`,
        queryColumn: 'id',
        order: 'ascending',
        column: 'id',
        curPage: 1,
        pageSize: 1,
        queryList: {
          columns: [
            { column: 'id',
              matchType: 'eq',
              value: `${this.selected}`
            }
          ]
        }
      }
      return getList(this.apiname, questArgs).then(ret => {
        if (ret.data.records) {
          const retRecords = ret.data.records.map((val) => {
            return { name: getMainName(this.apiname, val), value: val.id }
          })
          this.options = concatUniq(this.options, retRecords, (v1, v2) => {
            return v1.value === v2.value
          })
        }
        return this.options
      })
    },
    // 获取列表信息
    fetchData() {
      this.loading = true
      if (this.queryWith.length > 0) {
        this.queryWith.forEach(v => {
          this.listQuery[v.name] = v.value
        })
      }
      this.listQuery.column = getMainColName(this.apiname)
      this.listQuery.order = 'ascending'
      return getList(this.apiname, this.listQuery).then(ret => {
        this.loading = false
        this.listData = ret.data
        if (ret.data.records) {
          const retRecords = ret.data.records.map((val) => {
            return { name: getMainName(this.apiname, val), value: val.id }
          })
          this.options = concatUniq(this.options, retRecords, (v1, v2) => {
            return v1.value === v2.value
          })
        }
        return this.options
      })
    },
    // 选择改变时触发
    onSelectChanged(event) {
      console.log('selected', this.selected)
      this.$emit('change', event)
    },
    // 从服务器查询时触发
    remoteMethod(query) {
      if (query !== '') {
        this.listQuery.curPage = 1
        this.listQuery.query = query
        this.listQuery.queryColumn = getMainColName(this.apiname)
        this.listQuery.queryList = {
          columns: [
            { column: this.listQuery.queryColumn,
              matchType: 'like',
              value: query
            }
          ]
        }
        this.options = this.options.filter(v => v.value === this.selected)
        this.fetchData()
      }
    },
    clearMethod() {
      this.listQuery.queryList = {
        columns: []
      }
      this.options = []
      this.fetchData()
    },
    // 加载更多
    nextPage() {
      if (this.listData.current < this.listData.pages) {
        this.listQuery.curPage = this.listData.current + 1
        this.fetchData()
      }
    }
  }
}
</script>

<style scoped>
.line{
  text-align: center;
}
</style>

